package com.ysd.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ysd.dao.impl.ProductCategoryDaoImpl;
import com.ysd.dao.impl.ProductDaoImpl;
import com.ysd.entity.Product;
import com.ysd.entity.ProductCategory;

public class ProductsServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// request.setCharacterEncoding("UTF-8");
		
		// 调用实现类编写的方法
		// 产品分类
		ProductCategoryDaoImpl pcDao = new ProductCategoryDaoImpl();
		List<ProductCategory> pcList = pcDao.getAllProductCategories(); //从数据库获取的数据
		request.setAttribute("pcList", pcList);
		
		
		//接受前台传来的参数
		String pName = request.getParameter("productName"); //产品名
		String cateId = request.getParameter("cateId"); //产品分类Id
		ProductDaoImpl pDao = new ProductDaoImpl();
		
		if (cateId != null) { //如果cateId不为空, 那么代表按照分类id查询
			int categoryId = Integer.parseInt(cateId);// 转化为int类型
			List<Product> pList = pDao.getProductsByCateId(categoryId);
			request.setAttribute("pList", pList);
			request.setAttribute("categoryId", categoryId); //把接收到的categoryId存起来
		} else { //否则按照商品名称模糊查询
			List<Product> pList = pDao.getProductsByLike(pName);
			request.setAttribute("pList", pList);
		}
		
		
		//The method huodechanpin() is undefined for the type ProductCategoryDaoImpl
		
		//转发
		request.getRequestDispatcher("productlist.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
